package com.hospital.pet.love.lovepethospital.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.hospital.pet.love.lovepethospital.domain.User;
import com.hospital.pet.love.lovepethospital.resp.Result;
import com.hospital.pet.love.lovepethospital.resp.ResultCodeEnum;
import com.hospital.pet.love.lovepethospital.util.AuthenticationContextUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

/**
 * @author RoselleShaw
 * @create 2024-04-19 14:37
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private void responseNoLoginInfo(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        String json = JSON.toJSONString(Result.build(null, ResultCodeEnum.LOGIN_AUTH));
        // Spring Boot 自带的 Tomcat 默认使用了 getOutputStream() 来响应
        // 这里使用 getWriter() 会报错
        try (OutputStream outputStream = response.getOutputStream()) {
            outputStream.write(json.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 如果是跨域预检请求，直接放行
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        // 获取 token
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            responseNoLoginInfo(response);
            return false;
        }
        token = "user:login" + token;

        // 获取用户信息
        User user = JSON.parseObject(stringRedisTemplate.opsForValue().get(token), User.class);
        if (ObjectUtil.isNull(user)) {
            responseNoLoginInfo(response);
        }

        // 保存用户信息到 ThreadLocal 中
        AuthenticationContextUtil.set(user);

        // 重置 Redis 中用户信息的有效时间
        stringRedisTemplate.expire(token, 1, TimeUnit.HOURS);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        AuthenticationContextUtil.remove();
    }
}
